Adj=[[1,7],[2,7],[5],[2,4],[5],[],[7],[],[]] #graph on CLRS pp.550
V=xrange(len(Adj))
def topological_sort(Adj):
    answer=[]
    in_degree=[0]*len(V)
    for u in V:
        for v in Adj[u]:
            in_degree[v]+=1
    q=[]
    for u in V:
        if in_degree[u]==0:
            q.insert(0,u) #enqueue
    while len(q)>0: #queue not empty
        u=q.pop()
        answer.append(u)
        for v in Adj[u]:
            in_degree[v]-=1
            if in_degree[v]==0:
                q.insert(0,v)
    for u in V:
        if in_degree[u]!=0:
            raise Exception('Find a cycle in the graph')
    return answer

if __name__=='__main__':
    print 'Adj:', Adj
    ans=topological_sort(Adj)
    print 'Answer:', ans
